//
//  VCDrag.swift
//  ChapterAll ios11 新增拖放交互编程接口
//
//  Created by Kevin on 2020/4/21.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VC1Drag: UIViewController {
    
    lazy var dragInteraction = { ()-> UIDragInteraction in
        let interaction = UIDragInteraction(delegate: self)
        interaction.isEnabled = true
        return interaction
    }()
    
    lazy var dragView = { ()-> UIView in
        let ui = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        ui.backgroundColor = UIColor.red
        ui.addInteraction(self.dragInteraction)
        return ui
    }()
    
    lazy var dropInteraction = { ()-> UIDropInteraction in
        let interaction = UIDropInteraction(delegate: self)
        return interaction
    }()
    
    lazy var dropLabel = { ()-> UILabel in
        let ui = UILabel(frame: CGRect(x: 10, y: 300, width: 300, height: 30))
        ui.backgroundColor = UIColor.blue
        ui.isUserInteractionEnabled = true
        ui.addInteraction(self.dropInteraction)
        return ui
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(dragView)
        view.addSubview(dropLabel)
    }
}

extension VC1Drag: UIDragInteractionDelegate {
    
    func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
        let provider = NSItemProvider(object: "hello wrod" as NSItemProviderWriting)
        let item = UIDragItem(itemProvider: provider)
        return [item]
    }
}

extension VC1Drag: UIDropInteractionDelegate {
    
    func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
        return true
    }
    
    func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
        return UIDropProposal(operation: .copy)
    }
    
    func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
        let _ = session.loadObjects(ofClass: String.self) { (item) in
            self.dropLabel.text = item.first
        }
    }
}
